import 'package:flutter/material.dart';
import 'package:flutter_general/pages/scanner/scannerPageModel.dart';
import 'package:pkg_obz/export.dart';
import 'package:pkg_obz/widgets/dialog.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';

/// Create： Zhang 4/12/21 4:13 PM
/// 描述：扫描二维码
class ScannerPage extends PageStateful<ScannerPageModel> {
  ScannerPage() : super(pageModel: ScannerPageModel());

  @override
  Widget? rootView(BuildContext context) {
    var scanArea = (Display.screenWidth < 400 ||
            Display.screenHeight < 400)
        ? 200.0
        : 300.0;

    return Stack(
      alignment: Alignment.bottomCenter,
      children: [
        QRView(
          key: pageModel.qrKey,
          onQRViewCreated: (controller) {
            _onQRViewCreated(context, controller);
          },
          overlay: QrScannerOverlayShape(
            borderColor: Colors.red,
            borderRadius: 10,
            borderLength: 30,
            borderWidth: 10,
            cutOutBottomOffset: 100,
            cutOutSize: scanArea,
          ),
        ),
        Padding(
          padding: EdgeInsets.only(bottom: 50),
          child: InkWell(
            splashColor: Colors.transparent,
            highlightColor: Colors.transparent,
            onTap: () {
              pageModel.controller?.toggleFlash();
              pageModel.isFlashOn.value = !pageModel.isFlashOn.value;
            },
            child: Obz(
              () => pageModel.isFlashOn.value
                  ? Icon(
                      Icons.lightbulb_outline,
                      size: 50,
                      color: Colors.white,
                    )
                  : Icon(
                      Icons.lightbulb,
                      size: 50,
                      color: Colors.white,
                    ),
            ),
          ),
        ),
      ],
    );
  }

  //------------方法定义---------------

  ///扫码方法回调
  void _onQRViewCreated(BuildContext context, QRViewController controller) {
    pageModel.controller = controller;
    pageModel.controller!.scannedDataStream.listen(
      (scanData) {
        pageModel.barcode = scanData;
        if (pageModel.barcode != null) {
          pageModel.controller?.pauseCamera();
          toast(scanData.code);
          ZRouter.goBack();
        }
      },
    );
  }
//------------方法定义---------------
}
